<template>
  <!-- 注册页面的整体盒子 -->
  <div class="reg-container">
    <!-- 注册的盒子 -->
    <div class="reg-box">
      <!-- 标题的盒子 -->
      <div class="title-box"></div>
      <!-- 注册的表单区域 -->
      <!-- 验证表单的必填项
          :model="formData"  表单收集数据的对象
          :rules="rules"     验证规则对象
          ref="formRef"      兜底校验
       -->
      <el-form style="padding:0 25px" :model="loginForm" :rules="rules" ref="loginRef">
        <!-- prop="username" prop 指向具体的校验规则项 -->
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%" type="primary" @click="loginIn">登录</el-button>
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Reg',
  data(){
    return{
      // 收集表单数据的对象
      loginForm:{
        username:'hlf3510',
        password:'',
      },
      // 表单所有的校验规则的对象
      rules:{
        // 用户名校验
        username:[
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {pattern:/^[0-9a-zA-Z]{1,8}$/, message: '用户名的长度为6-10位,请重新输入', trigger: 'blur'}
        ],
        // 密码校验
        password:[
          {required: true, message: '请输入密码', trigger: 'blur'},
          {pattern:/^\S{6,15}$/, message: '请输入6-15位的密码', trigger: 'blur'}
        ],
      }
    }
  },
  methods:{
    // 1.绑定事件
    // 2.兜底校验
    // 3.发送axios请求
    // 4.获取token存入本地
    // 5.跳转到主页
    loginIn(){
       this.$refs.loginRef.validate(async (valid) => {
        if (!valid) return this.$message.error('信息填写错误')
          // alert('submit!');
          // 发送axios请求
          const {data:res} =  await this.$http.post('/api/login',this.loginForm)
          // 判断是否注册成功
          if(res.code!==0) return this.$message.error(res.message)
          this.$message.success(res.message)
          console.log(res)
          // 将token存入vuex中
          this.$store.commit('updateToken',res.token)
          // 登录成功跳转到主页
          this.$router.push('/')
      });
    },
  }
}
</script>

<style lang="less" scoped>
.reg-container {
  background: url('../../assets/images/login_bg.jpg') center;
  background-size: cover;
  height: 100%;

  .reg-box {
    width: 400px;
    height: 270px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .title-box {
      height: 60px;
      background: url('../../assets/images/login_title.png') center no-repeat;
    }
  }
}
</style>
